package org.texteasy;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class WarningActivity extends Activity implements OnClickListener, OnCheckedChangeListener{

	public static final String NUMBERS_EXTRAS = "org.texteasy.NUMBERS_EXTRAS";
	public static final String COUNT_EXTRAS = "org.texteasy.COUNT_EXTRAS";
	
	public static final int VERIZON_WARNING_COUNT = 10;
	
	public static final int GENERAL_WARNING_COUNT = 30;
	
	private String numbers;
	private int count;
	
	private AlertDialog verizonDialog;
	private AlertDialog warningDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Intent intent = getIntent();
		if(intent != null){
			String numbers = intent.getStringExtra(NUMBERS_EXTRAS);
			int count = intent.getIntExtra(COUNT_EXTRAS, 0);
			this.numbers = numbers;
			this.count = count;
		}
		
		Boolean verizonWarning = null;
		
		if (getLastNonConfigurationInstance() != null) {
			State config = (State) getLastNonConfigurationInstance();
			this.numbers = config.numbers;
			this.count = config.count;
			verizonWarning = config.verizonWarning;
		}
		
		SharedPreferences prefs = PreferenceManager
			.getDefaultSharedPreferences(this);
		//check if we changed orientation and had a dialog already open
		if(verizonWarning != null && verizonWarning.booleanValue()){
			
			createVerizonWarningDialog(prefs.getBoolean(
				getString(R.string.VERIZON_WARNING_PREF), false));
			
		}else if(verizonWarning != null && !verizonWarning.booleanValue()){
			
			if(!createGeneralWarningDialog()){
				startSMSActivity();
			}
			
		}else{
		
			
			if(!prefs.getBoolean(getString(R.string.VERIZON_WARNING_PREF), false) &&  
				this.count > VERIZON_WARNING_COUNT){
				
				createVerizonWarningDialog(false);
				
			}else if(this.count > GENERAL_WARNING_COUNT){
				
				createGeneralWarningDialog();
			}
		}
		
	}

	private void startSMSActivity() {
		
		SharedPreferences prefs = PreferenceManager
			.getDefaultSharedPreferences(this);
		
		Intent i = new Intent();
		i.setAction(Intent.ACTION_VIEW);
		i.setType("vnd.android-dir/mms-sms");
		i.putExtra("address", this.numbers);

		if(BulkMessenger.useCommaAsSeperator()){
			//if using a comma then other third party messaging may break
			//the plan is to check if the default messaging app exists and 
			//if so force that selection
			Intent testIntent = new Intent();
			testIntent.setAction(Intent.ACTION_VIEW);
			testIntent.setType("vnd.android-dir/mms-sms");
			
			for(ResolveInfo info: getPackageManager().queryIntentActivities(testIntent, 0)){
	        	if("com.android.mms".equalsIgnoreCase(info.activityInfo.packageName.toString())){
	        		i.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));
	        		break;
	        	}
	        }
		}
		String signature = prefs.getString(
				getString(R.string.ADD_SIGNATURE_TITLE), "");
		if (signature != null && !signature.equals("")) {
			i.putExtra("sms_body", "\n" + signature);
		}
		
		startActivityForResult(i, 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		finish();
	}
	
	private boolean createGeneralWarningDialog() {
		
		//this method is called from several places and may not 
		//need to show the message in all cases
		if(this.count > GENERAL_WARNING_COUNT){
			warningDialog = new AlertDialog.Builder(this).setTitle(
				R.string.Warning_Title).setNegativeButton(
				R.string.Return, this).
				setPositiveButton(R.string.Continue, this).
				create();
			LayoutInflater inflator = getLayoutInflater();
			View view = inflator.inflate(R.layout.general_warning, null);
			String message = getString(R.string.Warning_Content);
			message = message.replace("${count}", GENERAL_WARNING_COUNT + "");
			((TextView)view.findViewById(R.id.warning_dialog)).setText(message);
			warningDialog.setView(view);
			warningDialog.show();
			
			return true;
		}
		return false;
	}

	private void createVerizonWarningDialog(boolean checked) {
		verizonDialog = new AlertDialog.Builder(this).setTitle(
			R.string.Verizon_Warning_Title).setNegativeButton(
			R.string.Return, this).setPositiveButton(
			R.string.Continue, this).create();
		LayoutInflater inflator = getLayoutInflater();
		View view = inflator.inflate(R.layout.verizon_warning, null);
		((TextView)view.findViewById(R.id.verizon_dialog)).setText(R.string.Verizon_Warning_Content);
		CheckBox checkBox = (CheckBox)view.findViewById(R.id.ignore_verizon_warning); 
		checkBox.setText(R.string.Verizon_Warning_Ignore);
		checkBox.setOnCheckedChangeListener(this);
		//if user clicks the checkbox then rotates the screen then need to 
		//show the dialog again with the checkbox checked
		checkBox.setChecked(checked);
		verizonDialog.setView(view);
		verizonDialog.show();
	}
	
	public void onClick(DialogInterface dialog, int which) {
		
		if(dialog == verizonDialog){
			if(which == AlertDialog.BUTTON_POSITIVE){
				
				//display general warning if applicable
				verizonDialog.dismiss();
				
				if(!createGeneralWarningDialog()){
					startSMSActivity();
				}
				
			}else if(which ==AlertDialog.BUTTON_NEGATIVE){
				this.finish();
			}
		}else if(dialog == warningDialog){
			if(which == AlertDialog.BUTTON_POSITIVE){
				warningDialog.dismiss();
				startSMSActivity();
			}else if(which == AlertDialog.BUTTON_NEGATIVE){
				this.finish();
			}
		}
		
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		State toReturn = new State();
		toReturn.count = this.count;
		toReturn.numbers = this.numbers;
		if(this.verizonDialog != null){
			toReturn.verizonWarning = this.verizonDialog.isShowing();
		}else{
			toReturn.verizonWarning = false;
		}
		
		return toReturn;
	}
	
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		
		SharedPreferences prefs = PreferenceManager
			.getDefaultSharedPreferences(this);
		Editor editor = prefs.edit();
		if(isChecked){
			editor.putBoolean(getString(R.string.VERIZON_WARNING_PREF), true);
		}else{
			editor.putBoolean(getString(R.string.VERIZON_WARNING_PREF), false);
		}
		
		editor.commit();
	}
	
	private static class State{
		
		public String numbers;
		public int count;
		public boolean verizonWarning;
	}
}
